package cn.e4j.modular.api.controller;

import cn.digiwin.wx.utils.CookieUtils;
import cn.digiwin.wx.utils.WeixinHandler;
import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.cache.CacheUtil;
import cn.e4j.core.common.exception.BizExceptionEnum;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.JwtTokenUtil;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.api.service.UserServiceImpl;
import cn.e4j.modular.api.service.WXUserService;
import cn.e4j.modular.crm.entity.GwaaT;
import cn.e4j.modular.crm.mapper.GwaaTMapper;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.mapper.SysRoleModuleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述
 *
 * @author caijy
 * @description
 * @datetime 2019-10-8 0008 12:06
 * @return
 */
@RestController
@RequestMapping("/api/wx/user/")
public class UserApiController extends BaseController {

    @Autowired
    WXUserService wxUserService;

    @Autowired
    private GwaaTMapper gwaaTMapper;

    @Autowired
    private SysRoleModuleMapper sysRoleModuleMapper;

    @Autowired
    private UserServiceImpl userServiceImpl;

    /**
     * 获取微信用户信息+权限
     */
    @RequestMapping(value = "infos", method = RequestMethod.POST)
    public ResponseData infos(@DtoParam DtoWapper dtoWapper) {
        Dto dto = dtoWapper.getDto();
        SysUser user = dtoWapper.getSysUser();
        Map<String, Object> out = new HashedMap();
        List<Dto> list = new ArrayList<>();
//        dto.put("CASCADE_ID","0.003.004");
//        dto.put("ICON_NAME","icon-27");
//        dto.put("IS_LEAF","1");
//        dto.put("NAME","注册");
//        dto.put("SORT_NO",1);
//        dto.put("URL","register/register");
//        list.add(dto);
        try {
            dto.put("GWAA001", user.getACCOUNT());
            dto.put("GWAAACTI", "Y");
            dto.put("GWAAENT", user.getDBC());
            dto.put("USER_ID", user.getID());
            dto.put("CASCADE_ID", "0.005.");//微信问题提报模块
            out.put("user", gwaaTMapper.getGwaaUser(dto));
            out.put("auths", sysRoleModuleMapper.selectModulesOfWXUser(dto));
//            out.put("auths", list);
            out.put("sysUser", user);

        } catch (Exception e) {
            e.printStackTrace();
            return ERROR_TIP;
        }
        return new SuccessResponseData(out);
    }

    /**
     * 获取微信用户-未审核/已审核
     */
    @RequestMapping(value = "getGwaaNY", method = RequestMethod.POST)
    public ResponseData getGwaaNY(@DtoParam DtoWapper dtoWapper) {
        Dto dto = dtoWapper.getDto();
        Page page = dtoWapper.getPage();
        List<Dto> list;


        list = gwaaTMapper.getGWAATList(page, dto);
        list.stream().forEach(Gdto -> {

            if (Gdto.getString("GWAADATE") != null) {
                try {
                    LocalDateTime time = LocalDateTime.parse(Gdto.getString("GWAADATE"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    Gdto.put("GWAADATE", time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                } catch (DateTimeParseException e) {
                    Gdto.put("GWAADATE", Gdto.getString("GWAADATE"));
                }
            }

        });
        return new SuccessResponseData(list);
    }

    /**
     * 审核用户
     */
    @RequestMapping(value = "checkUser", method = RequestMethod.POST)
    public ResponseData checkUser(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        Dto outDto = new Dto();
        try {
            //匹配 微信账号是否在 后台已经提交注册了
            Dto param = new Dto();
            param.put("GWAA001", inDto.getString("GWAA001"));
            param.put("GWAAENT", inDto.getString("ENT"));
            param.put("GWAAACTI", "N");
            GwaaT user = wxUserService.getUserData(param);
            if (ToolUtil.isNotEmpty(user)) {
                return new ErrorResponseData(600, "用户已申请绑定，请等待管理员审核");
            }

            //判断是否是已审核用户
            param.put("GWAAACTI", "Y");
            user = wxUserService.getUserData(param);
            if (ToolUtil.isNotEmpty(user)) {
                return new ErrorResponseData(601, "用户已审核，不需要进行注册");
            }

            param.put("GWAAACTI", "T");
            param.put("GWAAACTI_NEW", "N");//新增 未审核
            //param.put("gwaatime", DateUtils.getTime());//资料时间
            //param.put("gwaadate", AppUtils.getDateTime());//资料建立日期
            param.put("GWAAENT", inDto.getString("ENT"));
            param.put("GWAA003", inDto.getString("GWAA001"));
            param.put("GWAA002", inDto.getString("GWAA002"));
            param.put("GWAA004", inDto.getString("GWAA004"));
            param.put("GWAA005", inDto.getString("GWAA005"));
            param.put("GWAA006", inDto.getString("GWAA006"));
            param.put("GWAA007", inDto.getString("GWAA007"));
            param.put("GWAA008", inDto.getString("GWAA008"));

            // 外部用户
            if (param.getString("GWAA007").equals("1")) {
                param.put("GWAA009", inDto.getString("GWAK001"));//交易对象编号
                param.put("GWAA011", inDto.getString("email"));
                param.put("GWAA013", inDto.getString("address"));
                param.put("GWAA017", inDto.getString("GWAA017"));
                param.put("GWAA018", inDto.getString("GWAA018"));
            }
            param.put("GWAAMODU", inDto.getString("GWAA001"));
            wxUserService.updateByKeyActi(param);

            //查询具有注册审核权限的用户的微信号
            Dto roleDto = Dtos.newDto();
            roleDto.put("GWAAENT", inDto.getString("ENT"));
            //roleDto.put("role_id_", "18052315553200117");//管理员
            //List<Dto> sysUser = systemService.getUserByRoleId(roleDto);
            List<Dto> sysUser = wxUserService.getGwaaByZcsh(roleDto);

            //通知所有管理员
            WeixinHandler.sendMsg(sysUser, "有新人员[" +
                    inDto.getString("GWAA002") + "," +
                    inDto.getString("GWAA004") + "]注册，请到销售服务审核！");

            outDto.setAppMsg("申请提交成功。\n请等待平台管理员审核！");
            outDto.put("data", inDto);

        } catch (Exception ex) {
            return new ErrorResponseData("注册异常！");
        }

        return new SuccessResponseData(outDto);
    }

    /**
     * 用户注册
     */
    @RequestMapping(value = "registerUser", method = RequestMethod.POST)
    public ResponseData registerUser(@DtoParam DtoWapper wapper) {

        Dto inDto = wapper.getDto();
        Dto outDto = new Dto();
        try {
            //匹配 微信账号是否在 后台已经提交注册了
            Dto param = new Dto();
            param.put("GWAA001", inDto.getString("GWAA001"));
            param.put("GWAAACTI", "N");
            GwaaT user = wxUserService.getUserData(param);
            if (ToolUtil.isNotEmpty(user)) {
                return new ErrorResponseData(600, "用户已申请绑定，请等待管理员审核");
            }

            //判断是否是已审核用户
            param.put("GWAAACTI", "Y");
            user = wxUserService.getUserData(param);
            if (ToolUtil.isNotEmpty(user)) {
                return new ErrorResponseData(601, "用户已审核，不需要进行注册");
            }

            param.put("GWAAACTI_Old", "T");
            param.put("GWAAACTI", "N");//新增 未审核
//            param.put("gwaatime", DateUtils.getTime());//资料时间
//            param.put("gwaadate", AppUtils.getDateTime());//资料建立日期
            param.put("GWAAENT", inDto.getString("ENT"));
            param.put("GWAA001", inDto.getString("GWAA001"));
            param.put("GWAA002", inDto.getString("GWAA002"));
            param.put("GWAA004", inDto.getString("GWAA004"));
            param.put("GWAA005", inDto.getString("GWAA005"));
            param.put("GWAA006", inDto.getString("GWAA006"));
            param.put("GWAA007", inDto.getString("GWAA007"));
            param.put("GWAA008", inDto.getString("GWAA008"));

            // 外部用户
            if (param.getString("GWAA007").equals("1")) {
                param.put("GWAA009", inDto.getString("GWAK001"));//交易对象编号
                param.put("GWAA011", inDto.getString("email"));
                param.put("GWAA013", inDto.getString("address"));
                param.put("GWAA017", inDto.getString("GWAA017"));
                param.put("GWAA018", inDto.getString("GWAA018"));
            }

//            param.put("GWAAMODU",inDto.getString("GWAA001"));
            wxUserService.updateByKeyActi(param);

            //查询具有注册审核权限的用户的微信号
            Dto roleDto = Dtos.newDto();
            //roleDto.put("role_id_", "18052315553200117");//管理员
            //List<Dto> sysUser = systemService.getUserByRoleId(roleDto);
            List<Dto> sysUser = wxUserService.getGwaaByZcsh(roleDto);

            //通知所有管理员
            WeixinHandler.sendMsg(sysUser, "有新人员[" +
                    inDto.getString("GWAA002") + "," +
                    inDto.getString("GWAA004") + "]注册，请到销售服务审核！");

            outDto.setAppMsg("申请提交成功。\n请等待平台管理员审核！");
            outDto.put("data", inDto);

        } catch (Exception ex) {
            ex.printStackTrace();
            return new ErrorResponseData("注册异常！");
        }

        return new SuccessResponseData(outDto);
    }

    /**
     * 判断账号是否存在或密码是否正确
     */
    @RequestMapping(value = "checkAccount", method = RequestMethod.POST)
    public ResponseData checkAccount(HttpServletRequest request, HttpServletResponse response, @DtoParam DtoWapper wapper) {

        Dto inDto = wapper.getDto();
        Dto outDto = new Dto();
        //匹配 微信账号是否在
        Dto param = new Dto();
        param.put("GWAA001", inDto.getString("username"));
        param.put("GWAAACTI", "N");
        GwaaT gwaa = wxUserService.getUserData(param);
        if (ToolUtil.isNotEmpty(gwaa)) {
            return new ErrorResponseData(600, "用户已申请绑定，请等待管理员审核");
        }
        //校验账号密码是否正确
        inDto.put("GWAA001", inDto.getString("username"));
        inDto.put("PASSWORD", ShiroKit.md5(inDto.getString("password")));
        Dto user = wxUserService.login(inDto);
        if (user == null) {
            return new ErrorResponseData(300, "账号或密码不正确，请重新输入！");
        } else {
            Map<String, String> prams = new HashMap<>();
            prams.put("_WX_ACCOUNT_", inDto.getString("username"));//企业微信帐号
            prams.put("_WX_USERNAME_", user.getString("NAME"));//用户名
            //prams.put("_WX_MOBILE_", "17858763690");
            prams.put("_WX_ID_", user.getString("ID"));
            prams.put("_WX_ORGID_", user.getString("ORG_ID"));
            //Dto user = sysUserMapper.getUser(sys_userPO.getID());
            prams.put("_TOKEN_", JwtTokenUtil.generateToken(String.valueOf(user.getString("ID"))));
            prams.put("_WX_ACTI_", "Y");
            CookieUtils.setCookie(request, response, prams);
            return ResponseData.success(200, "校验成功", user);
        }
    }

}
